package com.example.itcompanyinterview;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.itcompanyinterview.object.*;
import com.example.itcompanyinterview.tools.AboutDialog;
import com.example.itcompanyinterview.tools.ActivityAnimationSwitcher;
import com.example.itcompanyinterview.tools.CommonJsonParser;
import com.example.itcompanyinterview.tools.CommonUrlRequest;
import com.example.itcompanyinterview.tools.LoadingDialogHelper;
import com.example.itcompanyinterview.tools.MenuHelper;
import com.example.itcompanyinterview.tools.TitleBarGenerator;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class QuestionDetailActivity extends Activity {

	private InterviewQuestion question;
	private Handler messageHandler;
	private static String QUESTION_CONTROLER = "Question";
	private static String GET_QUESTION_CONTENT_ACTION = "GetQuestionContent";
	private static int GET_QUESTION_CONTENT = 0x04;
	
	private LoadingDialogHelper loadingHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_question_detail);
		//this.initActivityTitleBar();
		this.loadingHelper = new LoadingDialogHelper(this);
		this.setQuestion();
		this.initMessageHandler();
		this.getQuestionContentFromUrl();
	}

	private void initActivityTitleBar() {
		TitleBarGenerator titleBar = new TitleBarGenerator(this);
		titleBar.setTitleText("详情").setActionText("查看解答");
		titleBar.showTitleBar();
		this.setButtonClickAction();
	}

	private void setButtonClickAction() {
		Button answerButton = (Button) this.findViewById(R.id.title_action_button);
		answerButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Bundle bundle = new Bundle();
				bundle.putSerializable("question", question);
				final Intent intent = new Intent(QuestionDetailActivity.this,
						QuestionAnswerActivity.class);
				intent.putExtras(bundle);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				ActivityAnimationSwitcher.animationOut(findViewById(R.id.container), getWindowManager(),
						new ActivityAnimationSwitcher.AnimationFinishedListener() {
							@Override
							public void onAnimationFinished() {
								startActivity(intent);
							}
						});
				
			}
		});
	}
	
	private void setQuestion() {
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		this.question = (InterviewQuestion) bundle.getSerializable("question");
	}

	private void initMessageHandler() {
		this.messageHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == GET_QUESTION_CONTENT) {
					loadingHelper.closeLoadingDialog();
					String questionJsonString = (String) msg.obj;
					if (questionJsonString == null) {
						Toast.makeText(QuestionDetailActivity.this,
								"获取题目失败，请检测网络", Toast.LENGTH_SHORT).show();
						return;
					}
					initQuestionContent(questionJsonString);
				}
				super.handleMessage(msg);
			}

		};
	}

	private void getQuestionContentFromUrl() {
		new Thread(new Runnable() {
			public void run() {
				List<Pair<String, String>> paramList = new ArrayList<Pair<String, String>>();
				CommonUrlRequest.setParam(paramList, "questionid",
						String.valueOf(question.getId()));
				String roleQuestionString = CommonUrlRequest
						.getControllerAndAction(
								QuestionDetailActivity.QUESTION_CONTROLER,
								QuestionDetailActivity.GET_QUESTION_CONTENT_ACTION,
								paramList);
				Message m = messageHandler.obtainMessage();
				m.obj = roleQuestionString;
				m.what = QuestionDetailActivity.GET_QUESTION_CONTENT;
				messageHandler.sendMessage(m);
			}
		}).start();
		this.loadingHelper.showLoadingDialog();
	}

	private void initQuestionContent(String contentJson) {
		try {
			TextView titleView = (TextView) this
					.findViewById(R.id.questionTitle);
			TextView descriptionView = (TextView) this
					.findViewById(R.id.questionDescription);

			JSONObject jsonQuestionObj = CommonJsonParser
					.parseJsonObject(contentJson);
			if (jsonQuestionObj.getInt("err") != 0) {
				Toast.makeText(QuestionDetailActivity.this,
						"获取题目失败:" + jsonQuestionObj.getString("msg"),
						Toast.LENGTH_LONG).show();
				return;
			}

			JSONObject jsonQuestion = CommonJsonParser
					.parseJsonObject(jsonQuestionObj.getString("value"));
			
			String questionContent = jsonQuestion.getString("content");
			String questionAnswer = jsonQuestion.getString("answer");
			this.question.setQuestion(questionContent);
			this.question.setAnswer(questionAnswer);

			titleView.setText(this.question.getTitle());
			descriptionView.setText(this.question.getQuestion());
		} catch (JSONException e) {
			Toast.makeText(QuestionDetailActivity.this, "获取题目异常",
					Toast.LENGTH_LONG).show();
			Log.e("InitQuestionContent", e.getMessage());
		}
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	MenuHelper menuHelper = new MenuHelper(this, item);
    	menuHelper.processMenu();
    	return super.onOptionsItemSelected(item);
    }

	@Override
	protected void onResume() {
		ActivityAnimationSwitcher.animationIn(findViewById(R.id.container), getWindowManager());
		super.onResume();
	}
    
    

}
